package com.rankeiot.platform.controller;

import com.rankeiot.core.Current;
import com.rankeiot.core.anno.DataScope;


import com.rankeiot.core.data.UserInfo;
import com.rankeiot.core.data.response.Resp;
import com.rankeiot.core.util.StringUtil;
import com.rankeiot.platform.domain.Branch;

import com.rankeiot.core.anno.Auth;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import static com.rankeiot.core.util.LocaleUtil.t;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 组织机构管理
 **/
@Tag(name = "组织机构")
@Auth
@RestController
@RequestMapping("branch")
@RequiredArgsConstructor
public class BranchController {
    final SqlToyLazyDao dao;

    /**
     * 新增机构
     *
     * @param branch 机构信息
     * @return
     */
    @Operation(summary = "新增机构")
    @Transactional
    // @NoRepeatSubmit(HttpPart.body)
    @PostMapping("add")
    public Resp add(@Valid @RequestBody Branch branch) {

        String branchSN = "";
        if (branch.getPid() == null) {
            //branch.setPid(0L);
            //默认的父级sn
            // branch.setSn("");
            branchSN = (String) dao
                    .query()
                    .sql("SELECT max(sn) FROM t_branch WHERE pid is NULL")
                    .resultType(String.class)
                    .getOne();//.getSingleValue("SELECT max(sn) FROM t_branch WHERE pid is NULL")
            if (branchSN == null) {
                branchSN = "00";
            }
        } else {

            Map params = new HashMap<>(1);
            params.put("pid", branch.getPid());
            branchSN = (String) dao.getSingleValue("select max(sn) from " + Branch.TABLE + " WHERE pid=:pid", params);
            if (branchSN == null) {
                branchSN = (String) dao
                        .query()
                        .sql("SELECT sn FROM t_branch WHERE id = ?")
                        .values(branch.getPid())
                        .resultType(String.class)
                        .getOne();
                branchSN += "00";
            }
        }
        String sn=inc(branchSN);

        Current.user().assertBranch(sn,t("没有权限","hasn't permission"));

        branch.setSn(sn);
        dao.save(branch);
        return Resp.ok();
    }

    //序号加1
    private String inc(String sn) {
        if (StringUtil.isEmpty(sn)) {
            return sn;
        }
        int l = sn.length();
        long v = Long.parseLong(sn, Character.MAX_RADIX);
        String nv = Long.toString(v + 1, Character.MAX_RADIX);
        return StringUtil.leftPad(nv, '0', l);
    }

    /**
     * 删除机构
     *
     * @param branchs 需要删除的机构列表|[{id:"testId"}]
     * @return
     */
    @Operation(summary = "删除所选机构")
    @PostMapping("delete")
    public Resp delete(@RequestBody List<Branch> branchs) {
        dao.batchUpdate("update t_branch set is_del=1 where sn like concat(:sn,'%')", branchs);
        return Resp.ok();
    }

    /**
     * 保存机构
     *
     * @param branch
     * @return
     */
    @Operation(summary = "更新机构信息")
    @PostMapping("save")
    public Resp save(@Valid @RequestBody Branch branch) {
        Branch old = dao.load(branch);
        UserInfo userInfo = Current.user();

        userInfo.assertBranch(old.getSn(),t("没有权限","hasn't permission"));

        if ("0".equals(branch.getEnable()) && userInfo.getBranchId().equals(branch.getId() + "")) {
            Resp.fail(t("不能禁用自己的部门","cannot disable your own department"));
        }
        dao.update(branch);
        return Resp.ok();
    }

    /**
     * 查询部门信息详细
     *
     * @param query
     * @return
     */
    @GetMapping("detail")
    @Operation(summary = "获取机构详细信息")
    public Resp<Branch> detail(Branch query) {
        Branch branch = dao.load(query);
        return Resp.of(branch);
    }

    /**
     * 获取组织机构列表
     *
     * @param query
     * @return
     * @page
     */
    @Operation(summary = "获取组织机构列表")
    @RequestMapping("list")
    @DataScope(branch = "sn")
    public Resp<List<Branch>> list(Branch query) {
        //过滤权限
        List<Branch> result = dao.findBySql("branch_list", query);
        return Resp.of(result);
    }
}
